import requests
from bs4 import BeautifulSoup
import json
import csv
import os
from datetime import datetime
import time
import random


def fetch_nba_standings():
    """
    获取NBA东西部球队排名数据
    返回包含东西部排名的字典，或None(如果失败)
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://slamdunk.sports.sina.com.cn/'
    }

    url = "https://slamdunk.sports.sina.com.cn/rank#type=conference"

    try:
        print("正在获取NBA排名数据...")
        # 添加随机延迟避免被封
        time.sleep(random.uniform(1, 3))

        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = 'utf-8'

        if response.status_code != 200:
            print(f"请求失败，状态码：{response.status_code}")
            return None

        soup = BeautifulSoup(response.text, 'html.parser')

        # 初始化数据结构
        standings = {
            "Eastern": [],
            "Western": [],
            "update_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "source": url
        }

        # 查找所有排名表格 - 根据实际页面结构调整选择器
        conference_sections = soup.find_all('div', class_='conference-rank')

        if len(conference_sections) >= 2:
            # 东部排名
            east_teams = conference_sections[0].find_all('tr')[1:]  # 跳过表头
            for team in east_teams:
                cols = team.find_all('td')
                if len(cols) >= 10:
                    standings["Eastern"].append({
                        "rank": cols[0].get_text(strip=True),
                        "team": cols[1].get_text(strip=True),
                        "wins": cols[2].get_text(strip=True),
                        "losses": cols[3].get_text(strip=True),
                        "win_percentage": cols[4].get_text(strip=True),
                        "games_behind": cols[5].get_text(strip=True),
                        "last_10": cols[6].get_text(strip=True),
                        "streak": cols[7].get_text(strip=True),
                        "home_record": cols[8].get_text(strip=True),
                        "road_record": cols[9].get_text(strip=True)
                    })

            # 西部排名
            west_teams = conference_sections[1].find_all('tr')[1:]  # 跳过表头
            for team in west_teams:
                cols = team.find_all('td')
                if len(cols) >= 10:
                    standings["Western"].append({
                        "rank": cols[0].get_text(strip=True),
                        "team": cols[1].get_text(strip=True),
                        "wins": cols[2].get_text(strip=True),
                        "losses": cols[3].get_text(strip=True),
                        "win_percentage": cols[4].get_text(strip=True),
                        "games_behind": cols[5].get_text(strip=True),
                        "last_10": cols[6].get_text(strip=True),
                        "streak": cols[7].get_text(strip=True),
                        "home_record": cols[8].get_text(strip=True),
                        "road_record": cols[9].get_text(strip=True)
                    })

            return standings
        else:
            print("未找到排名数据表格，页面结构可能已变更")
            return None

    except Exception as e:
        print(f"获取数据时出错：{str(e)}")
        return None


def save_as_json(data, filename):
    """将数据保存为JSON文件"""
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print(f"数据已保存为JSON文件：{filename}")
        return True
    except Exception as e:
        print(f"保存JSON文件失败：{str(e)}")
        return False


def save_as_csv(data, filename):
    """将数据保存为CSV文件"""
    try:
        with open(filename, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            # 写入表头
            writer.writerow(["Conference", "Rank", "Team", "Wins", "Losses", "Win%",
                             "GB", "Last 10", "Streak", "Home", "Road"])

            # 写入东部数据
            for team in data["Eastern"]:
                writer.writerow([
                    "Eastern",
                    team["rank"],
                    team["team"],
                    team["wins"],
                    team["losses"],
                    team["win_percentage"],
                    team["games_behind"],
                    team["last_10"],
                    team["streak"],
                    team["home_record"],
                    team["road_record"]
                ])

            # 写入西部数据
            for team in data["Western"]:
                writer.writerow([
                    "Western",
                    team["rank"],
                    team["team"],
                    team["wins"],
                    team["losses"],
                    team["win_percentage"],
                    team["games_behind"],
                    team["last_10"],
                    team["streak"],
                    team["home_record"],
                    team["road_record"]
                ])
        print(f"数据已保存为CSV文件：{filename}")
        return True
    except Exception as e:
        print(f"保存CSV文件失败：{str(e)}")
        return False


def main():
    # 创建输出目录
    os.makedirs("nba_standings", exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    # 获取数据
    standings_data = fetch_nba_standings()

    if standings_data:
        # 保存数据
        json_file = f"nba_standings/nba_standings_{timestamp}.json"
        csv_file = f"nba_standings/nba_standings_{timestamp}.csv"

        save_as_json(standings_data, json_file)
        save_as_csv(standings_data, csv_file)

        # 打印摘要信息
        print("\n数据摘要：")
        if standings_data['Eastern']:
            top_east = standings_data['Eastern'][0]
            print(f"东部第一：{top_east['team']} ({top_east['wins']}胜{top_east['losses']}负)")

        if standings_data['Western']:
            top_west = standings_data['Western'][0]
            print(f"西部第一：{top_west['team']} ({top_west['wins']}胜{top_west['losses']}负)")
    else:
        print("未能获取排名数据")


if __name__ == "__main__":
    main()